<template>
  <div id="mainInfo" v-show="isShow">
    <p class="slogan">
      <i class="iconfont icon-bulb">&#xe603;</i>
      <span class="slogan-top">为了确保理赔时效，请准确填写以下报案信息</span></p>
    <div class="wrap">
      <group gutter="0" label-width="5.5em">
        <x-input
          :class="{default:!isDisabled,readonly:isDisabled}"
          :readonly="isDisabled"
          :show-clear="false"
          :max="32"
          title="报案人： "
          placeholder='姓名'
          v-model.trim="phoneForm.reporter"
        ></x-input>
        <x-input
          :class="{default:!isDisabled,readonly:isDisabled}"
          :readonly="isDisabled"
          :show-clear="false"
          title="联系电话："
          placeholder='手机号'
          v-model.trim="phoneForm.reporterPhone" type="tel" is-type="tel"
          :max="11"></x-input>
        <x-address
          :class="{disabled:isDisabled,default:!isDisabled,readonly:isDisabled}"
          id="address"
          title="事故地点："
          v-model=" phoneForm.acdntLocation"
          raw-value
          :list="addressData"
          value-text-align="left"
          placeholder='省/市/区县'
          confirmText="确定"
          cancelText="取消"
        ></x-address>
        <x-input
          :class="{default:!isDisabled,readonly:isDisabled}"
          :readonly="isDisabled"
          :show-clear="false"
          title="详细地址：" placeholder='请补充详细地址' v-model.trim="phoneForm.acdntSite"></x-input>
      </group>
    </div>
    <div class="wrap sec-part">
      <group gutter="0" label-width="5.5em">
        <x-input
          :class="{default:!isDisabled,readonly:isDisabled}"
          :readonly="isDisabled"
          :show-clear="false"
          title="损失金额："
          placeholder='金额（元）'
          v-model.trim="phoneForm.claimPrice"
          type="number">
        </x-input>
        <p class="slogan">* 小额案件快速赔付，大额案件需由保险公司现场查勘</p>
        <datetime
          :class="{disabled:isDisabled,default:!isDisabled,readonly:isDisabled}"
          class="time"
          title="事故时间："
          value-text-align="left"
          v-model="phoneForm.acdntAt"
          :min-year=2016
          :max-year=2100
          format="YYYY-MM-DD HH:mm"
          year-row="{value}年"
          month-row="{value}月"
          day-row="{value}日"
          hour-row="{value}点"
          minute-row="{value}分"
          confirm-text="完成"
          cancel-text="取消"></datetime>
        <popup-radio
          class="radios"
          title="物损类型："
          :class="{
          disabled:isDisabled,
          default:!isDisabled,
          readonly:isDisabled,
          radiosPHColor:phoneForm.acdntTypeCode === '' ? true : false
          }"
          :options="types"
          placeholder="请选择"
          v-model="phoneForm.acdntTypeCode"
          :disabled="true"></popup-radio>
        <popup-radio
          title="物损原因："
          class="radios"
          :class="{
          disabled:isDisabled,
          default:!isDisabled,
          readonly:isDisabled,
          radiosPHColor:phoneForm.acdntReasonCode === '' ? true : false
          }"
          :options="reasons"
          placeholder="请选择"

          v-model="phoneForm.acdntReasonCode"
        ></popup-radio>
        <x-textarea
          :class="{default:!isDisabled,readonly:isDisabled}"
          :readonly="isDisabled"
          id="textarea"
          :autosize="true"
          :max="180"
          name="description"
          :placeholder="('此处填写事故经过')"
          v-model.trim="phoneForm.acdntDesc"></x-textarea>
      </group>

    </div>
    <div class="step-next" style="margin-top: 20px; margin-bottom: 20px;">
      <x-button @click.native="submitForm">下一步</x-button>
    </div>
  </div>
  </div>
</template>

<script>
  import {
    Group,
    XInput,
    XAddress,
    ChinaAddressV3Data,
    Datetime,
    XTextarea,
    XButton,
    PopupRadio
  } from 'vux'
  import axios from '../api/config'
  //import {} from  '../api/api'
  export default{
    data(){
      return {
        isShow: false,
        waybillNo: '',
        phoneForm: {
          reporter: '',
          reporterPhone: '',
          acdntLocation: [],
          acdntSite: '',
          acdntAt: '',
          claimPrice: '',
          acdntTypeCode: '',
          acdntReasonCode: '',
          acdntDesc: ''
        },
        isDisabled: false,
        types: [],
        reasons: [],
        addressData: ChinaAddressV3Data,
      }
    },
    components: {
      Group,
      XInput,
      XAddress,
      Datetime,
      XTextarea,
      XButton,
      PopupRadio
    },
    mounted(){
      this.getParams()

    },
    computed: {
      formData() {
        let _now = new Date()
        let obj = {
          reporter: this.phoneForm.reporter,
          reporterPhone: this.phoneForm.reporterPhone,
          acdntLocation: this.phoneForm.acdntLocation.join(","),
          acdntSite: this.phoneForm.acdntSite,
          acdntAt: this.phoneForm.acdntAt + ':' + '00',
          claimPrice: this.phoneForm.claimPrice,
          acdntTypeCode: this.phoneForm.acdntTypeCode,
          acdntReasonCode: this.phoneForm.acdntReasonCode,
          acdntDesc: this.phoneForm.acdntDesc
        }
        console.log('obj=>',obj)
        return obj
      }
    },
    watch: {
      "$route"(to, from){
        this.getParams()
      }

    },
    methods: {
      /*获取出险原因 类型 的方法*/
      getParams(){
        this.waybillNo = this.$route.params.waybillNo
        //acdntTypes 类型
        function getAcdntTypes() {
          return axios.get('/config/acdntTypes');
        }

        //acdntReasons 原因
        function getAcdntReasons() {
          return axios.get('/config/acdntReasons');
        }

        axios.all([getAcdntTypes(), getAcdntReasons()])
        /* 两个请求现已完成  */
          .then(axios.spread((types, reasons) => {
              console.log("类型/原因", types, reasons)
              //下拉框格式 [{key:"key",value:"value"}]
              //把acdntTypeCode 换成 key
              //把acdntTypeName 换成 value
              var typeArr = []
              var reasonArr = []
              var typesData = types.data.data
              var reasonData = reasons.data.data
              for (var i = 0; i < typesData.length; i++) {
                typeArr.push(
                  {key: typesData[i].acdntTypeCode, value: typesData[i].acdntTypeName})
              }
              for (var i = 0; i < reasonData.length; i++) {
                reasonArr.push(
                  {key: reasonData[i].acdntReasonCode, value: reasonData[i].acdntReasonName})
              }
              this.types = typeArr
              this.reasons = reasonArr
              //先判断types 和 reason 是否加载完成
              //会出现undefined
              if(this.types && this.reasons)
                this.getFormData()
            })
          );

      },
      //查询理赔发起信息  /claims/{waybillNo1}/info
      getFormData(){
        let url = `/claims/${this.waybillNo}/info`
        let PolicyNo = JSON.parse(sessionStorage.getItem("parameter")).policyNo
        axios.get(url, {
          params: {
            policyNo: PolicyNo
          }
        })
          .then(res => {
            this.isShow = true
            //判断运单状态
            // eolinker 1 2 3 4 6 状态 可填写
            let resClaimStatus = res.data.data.claimStatus
            if (resClaimStatus === "NOT_EXIST" ||
              resClaimStatus === "DRAFT_MANUAL" ||
              resClaimStatus === "DRAFT_AUTO" ||
              resClaimStatus === "REJECT_TO_NETWORK" ||
              resClaimStatus === "REJECT_TO_ENTPR"
            ) {
              this.isDisabled = false
            } else {
              console.log(resClaimStatus)
              this.isDisabled = true
            }
            //有信息回显
            console.log("查询信息=>", res)
            let resDataClaim = res.data.data.claim
            if (resDataClaim) {
              //获取数据后 如果有出险时间 截掉秒数
              if (resDataClaim.acdntAt) {
                resDataClaim.acdntAt = resDataClaim.acdntAt.slice(0, resDataClaim.acdntAt.lastIndexOf(':'))
              }
              this.phoneForm = {
                reporter: resDataClaim.reporter,
                reporterPhone: resDataClaim.reporterPhone,
                acdntLocation: resDataClaim.acdntLocation === null ? ["", "", ""] : res.data.data.claim.acdntLocation.split(","),
                acdntSite: resDataClaim.acdntSite,
                acdntAt: resDataClaim.acdntAt,
                claimPrice: resDataClaim.claimPrice,
                acdntTypeCode: resDataClaim.acdntTypeCode,
                acdntReasonCode: resDataClaim.acdntReasonCode,
                acdntDesc: resDataClaim.acdntDesc,
              }
              if (!this.isDisabled) {
                this.getNowTime()
              }
              console.log(this.phoneForm)
              return
            } else {
              //无信息 清空表单
              this.getNowTime()
            }
          })
      },
      validation(){
        //校验规则
        //正则匹配手机号
        var reg = /^1(3[0-9]|4[57]|5[0-35-9]|7[0135678]|8[0-9])\d{8}$/
        var matching = reg.test(this.phoneForm.reporterPhone)
        console.log(this.phoneForm.claimPrice.length)
        //reporter 字符长度 0 ～ 32
        if (!this.phoneForm.reporter) {
          this.$toast('请填写报案人姓名')
          return false
        }
        //reporterPhone 验证有效手机号码
        else if (this.phoneForm.reporterPhone.length != 11) {
          this.$toast('请填写正确手机号')
          return false
        }
        else if (matching === false) {
          this.$toast('请填写正确手机号')
          return false
        }
        //省市区 不为空
        else if (this.phoneForm.acdntLocation.length === 0) {
          this.$toast('请选择事故地点')
          return false
        }
        //详细地址不为空
        else if (!this.phoneForm.acdntSite) {
          this.$toast('请填写详细地址')
          return false
        }
        //正则来源
        //http://www.tashan10.com/huo-bi-jin-e-javascriptzheng-ze-biao-da-shi/
        else if (!/^(([1-9]\d*)(\.\d{1,2})?)$|(0\.0?([1-9]\d?))$/.test(this.phoneForm.claimPrice)) {
          this.$toast('请输入有效金额')
          return false
        }
        //判断金额位数 限制10位整数 两位小数
        else if (parseFloat(this.phoneForm.claimPrice) >= 1000000000) {
          this.$toast('输入金额过大')
          return false
        }
        //选择出险类型
        else if (!this.phoneForm.acdntTypeCode) {
          this.$toast('请选择物损类型')
          return false
        }
        //选择出险原因

        else if (!this.phoneForm.acdntReasonCode) {
          this.$toast('请选择物损原因')
          return false
        }
        return true
      },
      //创建理赔单
      submitForm(){
        let url = `/claims/${this.waybillNo}/info`
        if (this.validation()) {
          /*
           *应后台要求 时间需要秒数
           *否则参数可以 直接写 this.phoneForm 传入对象
           * 不要试图先改acdntAt 会造成数据驱动视图变化
           */
          if (!this.isDisabled) { //如果有编辑权限  那么发起报案请求
            this.$vux.loading.show({
              text: '提交中'
            })
            console.log(this.phoneForm)
            console.log(this.formData)
            axios.post(url,
              this.formData
            ).then(res => {
              //添加loading
              console.log(this.waybillNo)
              if (res.data.meta.code === "SUCCESS") {
                this.$vux.loading.hide()
                this.$router.replace(
                  {
                    name: 'attach',
                    params: this.waybillNo
                  })
              }
            })
          } else {             //否则 直接跳转到下一页
            console.log('无编辑权限')
            this.$router.replace(
              {
                name: 'attach',
                params: this.waybillNo
              })

          }

        }
      },

      //获取当前时间
      getNowTime(){
        if (!this.phoneForm.acdntAt) {
          let now = new Date()
          let cmonth = now.getMonth() + 1
          let day = now.getDate()
          let hour = now.getHours()
          let minuter = now.getMinutes()
          if (cmonth < 10) cmonth = '0' + cmonth
          if (day < 10) day = '0' + day
          if (hour < 10) hour = '0' + hour
          if (minuter < 10) minuter = '0' + minuter
          this.phoneForm.acdntAt = now.getFullYear() + '-' + cmonth + '-' + day + ' ' + hour + ':' + minuter
        }
      }
    }
  }
</script>
<style lang="less" rel="stylesheet/less">
  @mainColor: #e6454a;
  @fontColor: #333333;
  @placeHolderColor: #999999;
  @borderColor: #bbbbbb;
  @defaultColor: #000000;
  @readonlyColor: #757575;
  #mainInfo {
    //默认黑色
    .default {
      .weui-cell__bd input,
      .vux-popup-picker-value,
      .vux-datetime-value,
      .vux-tap-active,
      #textarea .weui-cell__bd textarea{
        color: @defaultColor;
      }
    }
    //不可编辑是灰色
    .readonly {
      .weui-cell__bd input,
      .vux-popup-picker-value,
      .vux-datetime-value,
      .weui-cell__ft,
      #textarea .weui-cell__bd textarea{
        color: @readonlyColor;
      }
    }
    //下拉框
    //请选择时
    .radiosPHColor .weui-cell__ft {
      color: @placeHolderColor
    }
    //初始化每个项目距离
    .weui-cell {
      padding: 5px 15px 5px 0 !important;
    }
    //周边留白
    width: 90%;
    margin: 0 auto;
    //提示文字
    .slogan {
      font-size: 12px;
      padding: 5px 0;
      color: @mainColor;
      .slogan-top {
        vertical-align: middle;
      }
      .icon-bulb {
        display: inline-block;
        vertical-align: middle;
        font-size: inherit;
        text-rendering: auto;
        -webkit-font-smoothing: antialiased;
      }
      .icon-bulb::before {
        font-size: 16px;
        display: inline-block;
        margin-left: .2em;
        margin-right: .2em;
      }
    }
    //区域划分
    .wrap {
      border-radius: 5px;
      padding: 10px;
      background: #fff;
      border: 1px solid @borderColor;
      transform: rotate(0deg);
      -webkit-transform: rotate(0deg);
      font-weight: normal;
      font-style: normal;
    }
    .sec-part {
      margin-top: 10px;
    }

  }

  .disabled {
    pointer-events: none;
  }

  /*
  *覆盖vux样式
  */
  //去掉上下分栏线
  .weui-panel:before,
  .weui-cells:before,
  .weui-cells:after,
  .weui-cell:before,
  .vux-cell-box:before {
    height: 0 !important;
    border: 0 !important;
  }

  /*
  *更改字体大小
  *标准字体14px
  */
  .weui-cell{
    font-size: 14px;
  }
  .weui-cell__hd {
    font-size: 14px;
  }

  .vux-popup-picker-select {
    font-size: 14px;
    padding-left: 10px;
  }

  .vux-datetime {
    font-size: 14px;
  }

  .weui-cell__bd {
    padding-left: 10px;
    font-size: 14px;
    height: 30px;
    line-height: 100%;
    input {
      height: inherit;
      line-height: 100%;
    }
  }

  //输入框边框
  .weui-cell__bd,
  .vux-popup-picker-select-box,
  .vux-datetime-value {
    border-radius: 5px;
    border: 1px solid @borderColor;
  }

  //输入框尺寸
  .vux-popup-picker-select {
    height: 30px;
  }

  .vux-datetime-value {
    height: 30px;
    line-height: 30px;
    padding-left: 10px;
  }

  .weui-select {
    height: inherit !important;
    line-height: inherit !important;
    padding-left: 10px;
  }

  #address .weui-cell__ft {
    display: none;
  }

  /*
  *输入框内容排版
  *高度30px 上下居中
  */
  .vux-popup-picker-value {
    white-space: nowrap;
    display: inline-block;
    height: 30px;
    line-height: 30px;
  }

  .vux-popup-picker-placeholder {
    line-height: 30px;
    color: @placeHolderColor !important;
  }

  /*
  *限制宽度 不换行
  *事故地点
  *事故时间
  */
  #address .vux-popup-picker-value {
    white-space: nowrap;
    width: 80%;
    overflow: hidden;
    display: inline-block;
    margin: 0;
    padding: 0;
  }

  //宽度设置 需要使用flex
  /*.time .vux-datetime-value{
  }*/
  //设置 右侧图标
  .time .weui-cell__ft:after {
    right: 15px !important;
  }

  .weui-cell_select .weui-cell__bd:after {
    right: 30px !important;
  }

  #address .vux-popup-picker-select-box:after {
    content: " ";
    display: inline-block;
    height: 6px;
    width: 6px;
    border-width: 2px 2px 0 0;
    border-color: @borderColor;
    border-style: solid;
    -webkit-transform: matrix(0.71, 0.71, -0.71, 0.71, 0, 0);
    transform: matrix(0.71, 0.71, -0.71, 0.71, 0, 0);
    position: relative;
    top: -2px;
    position: absolute;
    top: 50%;
    margin-top: -4px;
    right: 31px;
  }

  //textarea
  #textarea {
    .weui-cell__bd {
      padding-top: 5px;
      height: inherit;
      font-size: 12px;
      line-height: inherit;
      background: #fff;
    }
    .weui-textarea {
      width: 99%;
      min-height: 40px;
    }
    .weui-textarea-counter {
      padding-right: 5px;
    }
  }

  //选择框禁用时样式
  .vux-selector-readonly {
    border-radius: 5px;
    border: 1px solid @borderColor;
    font-size: 14px;
    height: 30px;
    line-height: 30px;
    text-align: start !important;
    text-indent: 10px;
  }
  //单选框
  .weui-cells_radio{
    .weui-cell__bd{
      border: 0;
      font-size: 16px;
    }
    .weui-cell{
      padding: 10px 5px;

    }
  }
  .radios{
    .vux-cell-primary{
      flex: inherit;
    }
    .weui-cell__ft{
      border-radius: 5px;
      border: 1px solid @borderColor;
      height: 30px;
      line-height: 30px;
      text-align: left;
      padding-left: 10px;
      color: @defaultColor;
      flex:1
    }
  }
  .weui-cell_access .weui-cell__ft:after{
    right: 15px!important;
  }

</style>
